import Vue from 'vue'
import VueRouter from 'vue-router'
import {routers, otherRouter, menuRouter} from './router'
import UserToken from '../api/user_token'
import iView from 'iview'
import {isEmptyObject} from "../common/vue-expand-func";
import {CLEAR_LOGIN_DATA} from '../store/param/mutation_type'
import {profile} from "../config/base";
import {checkAccess} from "./permission";

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: routers
})

/**
 * 路由跳转前
 */
router.beforeEach((to, from, next) => {
  if (to.meta.title)
    document.title = to.meta.title

  /** 权限校验 **/
  if (!profile.isDev && !checkAccess(to.meta.access)) {
    router.replace({name: 'error_404'})
    return
  }

  iView.LoadingBar.start()
  router.app.$options.store.dispatch("pageChange",true)

  if (to.meta.notNeedToken) {
    /** 不需要token进入的页面 **/
    if (to.name === 'login' && UserToken.getUserToken()) {
      next({
        name: 'home_index'
      })
    } else {
      next()
    }
  } else {
    if (!UserToken.getUserToken()) {
      router.app.$options.store.commit(CLEAR_LOGIN_DATA)//清空登录数据
      next({
        name: 'login'
      })
    } else {
      UserToken.refreshToken()
      /** 检测是否存在该路由 **/
      toDefaultPage(to,next)
    }
  }
})

function toDefaultPage(to,next){
  let routerArr = [otherRouter, ...menuRouter]

  let parentRouter = {}
  let targetName=to.name==='otherRouter'?'home':to.name
  routerArr.map(item => {
    if (item.name === targetName){
      parentRouter = item
    }
  })
  if (!isEmptyObject(parentRouter)) {
    /** 符合一级路由的name就跳到二级路由的第一个 **/
    router.replace({
      name: parentRouter.children[0].name
    });
  }else{
    next()
  }
}

/**
 * 跳转后
 */
router.afterEach(() => {
  iView.LoadingBar.finish()
  router.app.$options.store.dispatch("pageChange", false)
})

export default router
